﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Collections.Generic;

namespace MvePublicService.RelationsOperations
{
	/*
	 * 日本SGI株式会社
	 * ヨハンソン・ヘンリク
	 * johansson@sgi.co.jp
	 * 
	 * Change Log:
	 * ---------------------------------------------------------------------------
	 * 2009.01.07	Johansson Henrik		Class Created.
	 * 2009.01.09							Updated GetRelationsBySegmentId, GetAllRelatedSegments
	 *										to always return an XML string.
	 *										Currently the application expect the reply to be an empty
	 *										Xml Document even if an exception is thrown or no matching 
	 *										data was founds.
	 */

	/// <summary>
	/// This static class provides methods for extracting, 
	/// updating and deleting Segment Relations in the Database.
	/// Use the static methods in this class to perform  
	/// Segment Relations related operations on the Database.
	/// </summary>
	/// <remarks>INSERT:Creds</remarks>
	internal static class RelationsManipulator
	{
		/// <summary>
		/// Get all segment relations that contain the given segment id.
		/// Original Name = GetRelations
		/// </summary>
		/// <remarks>Done</remarks>
		/// <param name="segmentId">Id to search for</param>
		/// <param name="connection">Sql Connection</param>
		/// <returns>The Xml string that contains the response document.</returns>
		internal static string GetRelationsBySegmentId(int segmentId, SqlConnection connection)
		{
			SqlCommand command = new SqlCommand();
			SqlDataReader reader = null;
			command.CommandTimeout = 60;

			XmlDocument doc = null;
			XmlElement dataRoot = XmlConstructor.FormatResponseDocument(ref doc);
			XmlElement dataNodeRoot = doc.CreateElement("segment_relations");
			dataRoot.AppendChild(dataNodeRoot);

			string result = string.Empty;
			try
			{
				command.Connection = connection;
				command.CommandType = System.Data.CommandType.StoredProcedure;
				command.CommandText = "GetRelationsBySegmentId";

				command.Parameters.Add("segmentId", SqlDbType.Int).Value = segmentId;

				reader = command.ExecuteReader();

				if (reader.HasRows)
				{
					if (doc != null)
					{
						while (reader.Read())
						{
							XmlElement relationTop = doc.CreateElement("segment_relation");
							dataNodeRoot.AppendChild(relationTop);

							int id1 = reader.GetInt32(0);
							int id2 = reader.GetInt32(1);
							int relation = reader.GetByte(2);

							XmlElement id1E = doc.CreateElement("id1");
							id1E.InnerText = id1.ToString();
							relationTop.AppendChild(id1E);

							XmlElement id2E = doc.CreateElement("id2");
							id2E.InnerText = id2.ToString();
							relationTop.AppendChild(id2E);

							XmlElement relationE = doc.CreateElement("relation");
							relationE.InnerText = relation.ToString();
							relationTop.AppendChild(relationE);
						}
					}
				}

				result = doc.OuterXml;
			}
			catch (SqlException ex)
			{
				MvePublicService.ErrorHandler.LogMessage(ex.Message, false);
				result = doc.OuterXml;
			}
			catch (InvalidOperationException ex)
			{
				MvePublicService.ErrorHandler.LogMessage(ex.Message, false);
				result = doc.OuterXml;
			}
			catch (IndexOutOfRangeException ex)
			{
				MvePublicService.ErrorHandler.LogMessage(ex.Message, false);
				result = doc.OuterXml;
			}
			finally
			{
				command.Dispose();
				if (reader != null)
				{
					reader.Close();
					reader.Dispose();
				}
			}

			return result;
		}//end:GetRelationsBySegmentId

		/// <summary>
		/// Get all related Segment given a Segment Id.
		/// Original Name = RelatedSegments
		/// </summary>
		/// <remarks>Done</remarks>
		/// <param name="segmentId">Id to search for</param>
		/// <param name="connection">Sql Connection</param>
		/// <returns>The Xml string that contains the response document.</returns>
		internal static string GetAllRelatedSegments(int segmentId, SqlConnection connection)
		{
			List<ClipOperations.Segment> _relatedSegments =
				new List<ClipOperations.Segment>();

			List<int> _segmentIdsToLoad =
				new List<int>();

			//Build The final result document
			XmlDocument doc = null;
			XmlElement dataRoot = XmlConstructor.FormatResponseDocument(ref doc);
			XmlElement resRoot = doc.CreateElement("segments");
			dataRoot.AppendChild(resRoot);

			string result = string.Empty;
			try
			{
				_segmentIdsToLoad =
					RelationLoader.FindRelatedSegmentIdsInDatabase(segmentId, connection);

				//Get each matching segment from the database.
				foreach (int relId in _segmentIdsToLoad)
				{
					ClipOperations.Segment segment =
						ClipOperations.SegmentLoader.LoadSegmentFromDatabase(relId, connection);

					if (segment != null)
						_relatedSegments.Add(segment);
				}

				foreach (ClipOperations.Segment segment in _relatedSegments)
				{
					ClipOperations.Clip clip =
						ClipOperations.ClipLoader.LoadClipFromDatabase(segment.ParentClipId, connection);

					if (clip != null)
					{
						XmlElement clipRoot = XmlConstructor.AddClipNodeToDocument(doc, clip, resRoot);
						XmlElement segmentRoot = XmlConstructor.AddSegmentNodeToClip(doc, segment, clip.OnAirDate, clipRoot);

						XmlElement kwRoot = doc.CreateElement("keywords");
						segmentRoot.AppendChild(kwRoot);

						List<KeywordOperations.Keyword> segmentKeywords =
							KeywordOperations.KeywordLoader.LoadKeywordsForSegmentFromDatabase(
							segment.Id, connection);

						if (segmentKeywords != null)
						{
							foreach (KeywordOperations.Keyword keyword in segmentKeywords)
							{
								XmlConstructor.AddKeywordNodeToSegment(
								doc, keyword, kwRoot);
							}
						}
					}
				}

				result = doc.OuterXml;

			}
			catch (Exception ex)
			{
				MvePublicService.ErrorHandler.LogMessage(ex.Message, false);
				result = doc.OuterXml;
			}
			return result;
		}//end:GetAllRelatedSegments
	}
}
